package top.oauth2.server.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import top.oauth2.common.constant.RedisConstant;
import top.oauth2.entity.security.Menu;
import top.oauth2.server.mapper.MenuMapper;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

/**
 * 创建一个资源服务ResourceServiceImpl，
 * 初始化的时候把资源与权限匹配关系缓存到Redis中，方便网关服务进行鉴权的时候获取。
 * 资源与角色匹配关系管理业务类
 * @author xphu
 * @version 1.0
 * @date 2021/8/26 16:09
 */
@Service
public class ResourceServiceImpl {

    private Map<String, List<String>> resourceRolesMap;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private MenuMapper menuMapper;


    /**
     * PostConstruct在构造函数之后执行
     */
    @PostConstruct
    public void initData(){
        //查询全部的接口和对应的权限
        LambdaQueryWrapper<Menu> wrapper = new LambdaQueryWrapper<Menu>()
                .eq(Menu::getType, 1)
                .eq(Menu::getStatus, 1);
        List<Menu> menuList = menuMapper.selectList(wrapper);
        resourceRolesMap = new TreeMap<>();
        menuList.forEach(menu -> {
            resourceRolesMap.put(menu.getPath(), CollUtil.toList(menu.getPermissionValue().split(",")));
        });
        redisTemplate.opsForHash().putAll(RedisConstant.RESOURCE_MENU_MAP, resourceRolesMap);
    }
}
